<?php

namespace App\Http\Controllers\Back;

use App\Model\ArticleLabel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleLabelController extends Controller
{

    /**
     * 文章标签列表
     * @return \Illuminate\Http\Response
     */
    public function getArticleLabels()
    {

        $list = ArticleLabel::where("is_deleted", 0)->get();

        return $this->renderJson($list);
    }

    /**
     * 查找单个文章标签
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function getArticleLabel($id)
    {
        $article = ArticleLabel::where("id", $id)->first();

        return $this->renderJson($article);
    }

    /**
     * 新增文章标签
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function addArticleLabel(Request $request)
    {
        $article = new  ArticleLabel();

        $article->name = $request->input("name");
        $article->sort = $request->input("sort");
        $res = $article->save();
        if ($res == true) {
            return $this->renderJson("保存成功！");
        }
        return $this->renderJson("保存失败！");
    }

    /**
     * 修改单个文章标签
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function updateArticleLabel(Request $request, $id)
    {
        $article = ArticleLabel::where("id", $id)->first();
        if ($name = $request->input('name')) {

            $article->name = $name;
        }
        if ($sort = $request->input('sort')) {
            $article->sort = $sort;
        }

        $res = $article->save();
        if ($res == true) {
            return $this->renderJson("修改成功！");
        }
        return $this->renderJson("修改失败！");

    }

    /**
     * 删除文章 标签
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function deletedArticleLabels(Request $request)
    {
        $id = $request->input('id');

        for ($i = 1; $i < count($id); $i++) {
            $article = ArticleLabel::where("id", $id[$i])->first();
            $article->is_deleted = (bool)$request->input("is_deleted");
            $article->save();
        }

        return $this->renderJson([]);
    }

}
